package com.example.room;

import android.content.Context;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.room.dao.StudentDao;
import com.example.room.database.StudentDataBase;
import com.example.room.entity.Student;

import java.util.List;

//通过StudentRepository这个类进行dao的获取以及数据库的操作
public class StudentRepository {

    private StudentDao studentDao;

    //通过构造方法获取dao
    public StudentRepository(Context context) {
        StudentDataBase database = StudentDataBase.getInstance(context);
        this.studentDao = database.getDao();
    }

    //增加
    public void insertStudent(Student... students) {
        new insertStudentTask(studentDao).execute(students);
    }

    public class insertStudentTask extends AsyncTask<Student, Void, Void> {

        private StudentDao studentDao;

        public insertStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
            studentDao.insetStudent(students);
            return null;
        }
    }

    //删除
    public void deleteStudent(Student... students) {
        new deleteStudentTask(studentDao).execute(students);
    }

    public class deleteStudentTask extends AsyncTask<Student, Void, Void> {
        private StudentDao studentDao;

        public deleteStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
            studentDao.deleteStudent(students);
            return null;
        }
    }

    //修改
    public void updateStudent(Student... students) {
        new updateStudentTask(studentDao).execute(students);
    }

    public class updateStudentTask extends AsyncTask<Student, Void, Void> {
        private StudentDao studentDao;

        public updateStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
            studentDao.updateStudent(students);
            return null;
        }
    }

    //查询所有
    public LiveData<List<Student>> queryAllStudent() {
        return studentDao.getAll();
    }

    //删除所有
    public void deleteAllStudent() {
        new deleteAllStudentTask(studentDao).execute();
    }

    public class deleteAllStudentTask extends AsyncTask<Void, Void, Void> {
        private StudentDao studentDao;

        public deleteAllStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }


        @Override
        protected Void doInBackground(Void... voids) {
            studentDao.deleteAllStudent();
            return null;
        }
    }

}




